package com.wft.design.upms.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wft.design.common.mybatis.service.impl.BaseServiceImpl;
import com.wft.design.upms.entity.SysRole;
import com.wft.design.upms.entity.SysRoleMenu;
import com.wft.design.upms.mapper.SysMenuMapper;
import com.wft.design.upms.mapper.SysRoleMenuMapper;
import com.wft.design.upms.service.SysRoleMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author WFT
 * @date 2020/3/13
 * description:
 */
@Service
@RequiredArgsConstructor
public class SysRoleMenuServiceImpl extends BaseServiceImpl<SysRoleMenuMapper, SysRoleMenu>
        implements SysRoleMenuService {

    private final SysMenuMapper menuMapper;


    @Override
    public List<Long> selectMenuIdListByRoleId(Long roleId) {
        return this.list(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId,roleId))
                .stream()
                .map(SysRoleMenu::getMenuId)
                .collect(Collectors.toList());
    }

    @Override
    public void updateMenuListByRoleId(SysRole role) {
        //  删除角色原先绑定的菜单
        this.remove(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId,role.getId()));
        //  判断是否需要重新设置菜单与角色的绑定关系
        if (!role.getMenuIdList().isEmpty()){
            StringBuffer buffer = new StringBuffer();
            role.getMenuIdList().forEach(menuId -> buffer.append(menuId).append(","));
            //  获取菜单Id列表
            List<Long> menuIdList = this.menuMapper.selectIdsByChildrenIds(buffer.substring(0,buffer.length() - 1));
            List<SysRoleMenu> entityList = new ArrayList<>(menuIdList.size());
            menuIdList.forEach(menuId -> entityList.add(new SysRoleMenu(role.getId(),menuId)));
            this.saveBatch(entityList);
        }
    }

}
